package cn.oscar.controller;


import commonUtils.entities.Restful;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 通用的控制层，用于文件上传下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommenController {

    @Value("${photo.path}")
    private String basePath;

    /**
     * 文件上传功能，转存路径在yml中的photo.path中设置
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Restful<String> upload(MultipartFile file){
        //这里上传的file存放的是一个临时文件，在本次请求结束后会被删除，需要转存位置
        //创建自定义目录对象
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdir();
        }
        //将file对象转存在新位置
        String originalFilename = file.getOriginalFilename();
        //原文件的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重新进行拼接文件名
        String name = UUID.randomUUID().toString() + suffix;
        try {
            file.transferTo(new File(basePath + name ));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Restful.success(name);
    }


    /**
     * 文件下载功能
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //输入流，读取文件内容
        try {
            FileInputStream inputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流写回浏览器，在浏览器显示图片
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应回去是是图片图片
            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while((len=inputStream.read(bytes)) != -1 ){
                outputStream.write(bytes,0,len);
            }
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
